// errorReport.js
const app = getApp()
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
var util = require("../../utils/util.js")
const qiniuUploader = require("../../utils/qiniuUploader.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    form:{
      SN: '',
      phone: '',
      problem: '',
    },
    num:0,
    line:'400-060-2006',
    uploadPicture:[],
    maxCount:2,
    isInCount:true
  },
  onChange(detail, event) {// detail 为当前输入的值
    this.setData({
      [detail]: event.detail
    })
  },
  SNChange: function (event) {
    this.onChange('form.SN', event)
  },
  telChange: function (event) {
    this.onChange('form.phone', event)
  },
  proChange: function (event) {
    this.onChange('form.problem', event);
    var num = this.data.form.problem.value.length;
    this.setData({
      num,
    })
  },
  lineTap:function(){
    wx.makePhoneCall({
      phoneNumber: this.data.line
    })
  },
  // 上传图片
  afterRead:function(event) {
    let that = this;
    let { uploadPicture } = that.data
    // 通过微信的api选择图片，暂存到本地文件夹，并且通过路径名可以拿到该图片
    wx.chooseImage({
      sizeType: ['original'],
      sourceType: ['album','camera '],
      success: function (res) {
        var filePath = res.tempFilePaths[0];
        app.fetchUptoken().then(function (res) { //异步变同步
          let uptoken = res.data.data.token
          let region = res.data.data.region
          let domain = res.data.data.domain
          let key = res.data.data.key
          console.log(uptoken)
          //使用引入的qiniuUploader方法调七牛上传的接口
          qiniuUploader.upload(filePath, (res) => {  //回调 success
            var file = {
              fileUrl: "http://"+res.fileUrl,
              imageURL: "http://" +res.imageURL}
            uploadPicture = uploadPicture.concat(file);
            that.setData({
              uploadPicture: uploadPicture,
            })
            if (that.data.uploadPicture.length >= that.data.maxCount) {
              that.setData({
                isInCount: false
              })
            }
          }, (error) => { //回调 fail
            console.log('error: ' + error);
          },{ // 参数设置
            region: region,
            domain: domain,
            key: key,
            uptoken: uptoken
          }), (res) => {
            console.log('上传进度', res.progress)
            console.log('已经上传的数据长度', res.totalBytesSent)
            console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
          }
        })
      }
    })

  },
  // 删除图片
  deleteItem:function(event){
    var that = this;
    const index = event.currentTarget.dataset.index;
    var list = this.data.uploadPicture;
    list.splice(index,1)
    that.setData({
      uploadPicture: list
    })
    if (that.data.uploadPicture.length < that.data.maxCount) {
      that.setData({
        isInCount: true
      })
    }
  },
  // 提交
  submit:function(){
    var that = this;
    var imgArr = [];
    if (that.data.uploadPicture.length>0){
      for (var i in that.data.uploadPicture) {
        imgArr.push(that.data.uploadPicture[i].imageURL)
      }
    }
    var data = { 
      sn:that.data.form.SN,
      tel: that.data.form.phone,
      message: that.data.form.problem.value,
      images: imgArr,
      info: '用户信息：'+JSON.stringify(app.globalData.userInfo) +'————version:'+that.data.version+'————codeUrl:'+app.globalData.codeUrl+'————订单详情：'+ JSON.stringify(app.globalData.order),
    }
    if (that.data.form.SN !== '' && that.data.form.phone !== '' && that.data.form.problem !== '' && imgArr.length!==0 ) {
      app.post('order/fault',data).then((res)=>{
        console.log(res)
        if(res.code==200){
          Toast({
            type: 'success',
            message: res.message,
            duration:3000,
            onClose: () => {
              wx.switchTab({
                url: '../map/map',
              })
            },
          });
        }else{
          wx.showToast({
            icon: "loading",
            title: '提交失败',
          })
        }
      }).catch((errMsg)=>{
        console.log(errMsg)
      })
    }else{
      wx.showToast({
        title: '请填写完整',
        icon: 'none',
        duration: 3000
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      ['form.SN']:options.sn,
      version:options.version
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  }
})